using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using cframework_xlua;
using Newtonsoft.Json;

namespace cframework_xlua
{
    [EssentialTools("bash", "https://git-scm.com/downloads")]
    [CreateAssetMenu(menuName = "cframework_xlua/ChannelUtil_Pgy")]
    public class ChannelUtil_Pgy : ChannelUtil
    {
        [Essential]
        public string apiKey;

        public override bool Deploy(BuildPlayerSetting bps, string appPath, string destPath, string paramStr, ref string downloadUrl)
        {
            MonoScript script = MonoScript.FromScriptableObject(this);
            string path = AssetDatabase.GetAssetPath(script);
            path = System.IO.Path.GetFullPath(path);
            string shScriptDir = System.IO.Path.GetDirectoryName(path);

            downloadUrl = null;
            var shPath = bps.deviceToolPaths.GetCmdToolPath("bash");
            var ret = CommandLineTool.RunCommand2(shPath, $"pgyer_upload.sh -k {apiKey} {appPath}", shScriptDir);
            if (ret.ExitCode != 0)
            {
                Debug.LogError("output: " + ret.StdOut);
                Debug.LogError("error: " + ret.StdErr);

                return false;
            }
            else
            {
                string s = ret.StdOut.Substring(ret.StdOut.IndexOf("{\"code\":"));
                var a = JsonConvert.DeserializeObject<Dictionary<string, object>>(s);
                // Debug.Log("output: " + s + " " + a["data"] + " " + a["data"].GetType());

                string buildShortcutUrl = (a["data"] as Newtonsoft.Json.Linq.JObject)["buildShortcutUrl"].ToString();
                downloadUrl = $"https://www.pgyer.com/{buildShortcutUrl}";
            }

            return true;
        }
    }
}